package com.ai.sml.filter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ai.sml.util.DateUtil;
import com.ai.sml.util.PropertiesUtil;
import com.ai.sml.util.WebUtils;

public class CsrfFilter implements Filter {

	private static Logger LogForCsrf = Logger.getLogger("LogForCsrf");

	// 白名单
	private List<String> whiteUrls;
	
	private int _size = 0;

	public void init(FilterConfig filterConfig) {
		String path = CsrfFilter.class.getResource("/").getFile();
		whiteUrls = readFile(path + "csrfWhite.txt");
		// 读取文件
		// whiteUrls =
		// readFile("/home/zyzx/apps-share/mall/mall/WEB-INF/classes/csrfWhite.txt");
		_size = null == whiteUrls ? 0 : whiteUrls.size();
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;
			// 获取请求url地址
			String url = req.getRequestURL().toString();
			String referurl = req.getHeader("Referer");
			LogForCsrf.info("referurl----->"+referurl);
			if (isWhiteReq(referurl)) {
				chain.doFilter(request, response);
			} else {

				req.getRequestDispatcher("/").forward(req, res);

				String clientIp = WebUtils.getCurrentIP(req);

				String date = DateUtil.date2String(new Date());

				// sessionId + date + referurl + url + clientIp + phoneNo
				// 记录跨站请求日志
				String log = clientIp + "||" + date + "||" + referurl + "||" + url;
				LogForCsrf.warn(log);
				return;
			}

		} catch (Exception e) {
			LogForCsrf.error("doFilter", e);
			e.printStackTrace();
		}

	}

	/*
	 * 判断是否是白名单
	 */
	private boolean isWhiteReq(String referURL) {
		if (referURL == null || "".equals(referURL) || _size == 0) {
			return true;
		} else {
			String refHost = "";
			String referUrl = referURL.toLowerCase();
			if (referUrl.startsWith("http://")) {
				refHost = referUrl.substring(7);
			} else if (referUrl.startsWith("https://")) {
				refHost = referUrl.substring(8);
			}
			
			for (String urlTemp : whiteUrls) {
				if (refHost.indexOf(urlTemp.toLowerCase()) > -1) {
					return true;
				}
			}
		}

		return false;
	}

	public void destroy() {
	}
	
	private List<String> readFile(String fileName){
		List<String> list = new ArrayList<String>();
		File f = new File(fileName);
		if (f.isFile() && f.exists()) {
			try (InputStreamReader read = new InputStreamReader(new FileInputStream(f), "UTF-8");
					BufferedReader reader = new BufferedReader(read);) {
				String line;
				while((line=reader.readLine()) != null){
					if(!"".equals(line)){						
						list.add(line);
					}
				}
				read.close();

			} catch (Exception e) {
				//e.printStackTrace();
				LogForCsrf.error("",e);
			}
		}
		return list;
	}
}
